from fastapi import FastAPI, HTTPException, Query, APIRouter
from datetime import datetime
from typing import Optional
import uvicorn
from pydantic import BaseModel
from stock_day import sync_stock_day_to_db  # 最新方法名称

app = FastAPI()
router = APIRouter()


class StockSyncResponse(BaseModel):
    success: bool
    message: str
    records: int
    stock_code: str
    stock_name: str
    date_range: str


# 同时支持 GET 和 POST
@router.api_route("/api/stocks/sync", methods=["GET", "POST"], response_model=StockSyncResponse)
async def sync_stock_data(
    stock_code: str = Query(..., description="股票代码"),
    stock_name: str = Query(..., description="股票名称"),
    start_date: Optional[str] = Query(
        None,
        pattern="^\\d{8}$",
        description="开始日期(YYYYMMDD)"
    ),
    end_date: Optional[str] = Query(
        None,
        pattern="^\\d{8}$",
        description="结束日期(YYYYMMDD)"
    )
):
    try:
        result = sync_stock_day_to_db(
            stock_code=stock_code,
            stock_name=stock_name,
            start_date=start_date,
            end_date=end_date
        )

        if not result["success"]:
            raise HTTPException(status_code=400, detail=result["message"])

        date_range = f"{start_date or end_date} ~ {end_date or start_date}"
        return {
            "success": result["success"],
            "message": result["message"],
            "records": result["records"],
            "stock_code": stock_code,
            "stock_name": stock_name,
            "date_range": date_range
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务端错误: {str(e)}")


app.include_router(router)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
